import {useEffect, useRef, useState} from "react";
import './datePicker.scss';
import rabbit from '../rabbit.jpeg';

export default function DatePicker({dateState}) {
    const [date, setDate] = dateState;
    const [localDate, setLocalDate] = useState(date);
    const [showPicker, setShowPicker] = useState(false);
    const [days, setDays] = useState([]);
    const today = new Date();

    const wrapperRef = useRef(null);
    useOutsideAlerter(wrapperRef, () => setShowPicker(false));

    const handlePickClick = (item) => {
        if (item === -1) return;
        let selected = new Date(localDate);
        selected.setDate(item);
        setDate(selected);
    };

    const previousYear = () => {
        let newDate = new Date(localDate);
        newDate.setFullYear(localDate.getFullYear() - 1);
        setLocalDate(newDate);
    };

    const nextYear = () => {
        let newDate = new Date(localDate);
        newDate.setFullYear(localDate.getFullYear() + 1);
        setLocalDate(newDate);
    };

    const previousMonth = () => {
        let newDate = new Date(localDate);
        let month = newDate.getMonth();
        if (month === 0) {
            newDate.setMonth(11);
            newDate.setFullYear(newDate.getFullYear() - 1);
        } else {
            newDate.setMonth(month - 1);
        }
        setLocalDate(newDate);
    };

    const nextMonth = () => {
        let newDate = new Date(localDate);
        let month = newDate.getMonth();
        if (month === 11) {
            newDate.setMonth(0);
            newDate.setFullYear(newDate.getFullYear() + 1);
        } else {
            newDate.setMonth(month + 1);
        }
        setLocalDate(newDate);
    };

    const isToday = (item) => {
        const year = localDate.getFullYear();
        if (year !== today.getFullYear()) {
            return false;
        }
        const month = localDate.getMonth();
        if (month !== today.getMonth()) {
            return false;
        }
        return today.getDate() === item;
    }

    const isSelected = (item) => {
        const year = date.getFullYear();
        if (year !== localDate.getFullYear()) {
            return false;
        }
        const month = date.getMonth();
        if (month !== localDate.getMonth()) {
            return false;
        }
        return date.getDate() === item;
    }

    useEffect(() => {
        let firstDayOfTheMonth = new Date(localDate);
        firstDayOfTheMonth.setDate(1);
        const numOfDays = new Date(localDate.getFullYear(), localDate.getMonth() + 1, 0).getDate();
        const days = [];
        for (let i = 0; i < firstDayOfTheMonth.getDay(); i++) {
            days.push(-1);
        }
        for (let i = 0; i < numOfDays; i++) {
            days.push(i + 1)
        }
        setDays(days);
    }, [date, localDate]);



    if (date === null) {
        return (
            <div>加载中</div>
        );
    }


    return (
        <div className={'date-picker'}>
            <div>
                <div>{date.getFullYear()} / {date.getMonth() + 1} / {date.getDate()}</div>
                <button onClick={() => setShowPicker(true)}>选择</button>
            </div>
            <div className={'date-picker-calender'} ref={wrapperRef} style={{
                visibility: showPicker ? 'visible' : 'hidden',
                opacity: showPicker ? 1 : 0
            }}>
                <img className={'rabbit'} src={rabbit} alt={'星黛露'}/>
                <div className={'head'}>
                    <div>{localDate.getFullYear()} 年</div>
                    <div>{localDate.getMonth() + 1} 月</div>
                    <button onClick={previousMonth}>上个月</button>
                    <button onClick={nextMonth}>下个月</button>
                </div>
                <div className={'body'}>
                    <div className={'days'}>
                        <div className={'day'}>周日</div>
                        <div className={'day'}>周一</div>
                        <div className={'day'}>周二</div>
                        <div className={'day'}>周三</div>
                        <div className={'day'}>周四</div>
                        <div className={'day'}>周五</div>
                        <div className={'day'}>周六</div>
                    </div>
                    <div className={'dates'}>
                        {days.map((item, key) =>
                                <div className={item === -1 ? 'date disabled' : 'date'}
                                     key={key}>
                                    <div className={
                                        'inner-date' +
                                        (isToday(item) ? ' today' : '')  +
                                        (isSelected(item) ? ' selected' : '')}
                                         onClick={() => handlePickClick(item)}>
                                        {item === -1 ? '' : item}
                                    </div>
                                </div>
                        )}
                    </div>

                </div>
            </div>
        </div>
    );
}

function useOutsideAlerter(ref, fn) {
    useEffect(() => {
        /**
         * Alert if clicked on outside of element
         */
        function handleClickOutside(event) {
            if (ref.current && !ref.current.contains(event.target)) {
                fn();
            }
        }

        // Bind the event listener
        document.addEventListener("mousedown", handleClickOutside);
        return () => {
            // Unbind the event listener on clean up
            document.removeEventListener("mousedown", handleClickOutside);
        };
    }, [ref]);
}
